import { effect } from "./effect";
interface Options {
  immediate?: boolean;
  flush?: 'sync' | 'post' | 'pre'
}
const traverse = (target, seen = new Set()) => {
  if(typeof target !== 'object' || target === null || seen.has(target)) return;
  seen.add(target)
  for(let key in target) {
    traverse(target[key], seen)
  }
  return target;
}
export const watch = (target: any, cb: Function, options?: Options) => {
  // 格式化参数 =》 getter函数
  let getter: Function
  if(typeof target === 'function') {
    getter = target
  } else {
    getter = () => traverse(target)
  }
  // 需要返回值
  let newValue,oldValue
  const job = () => {
    newValue = effectFn()
    cb(newValue, oldValue)
    oldValue = newValue
  }
  const effectFn = effect(getter, {
    lazy: true,
    scheduler: job
  })
  // 支持immediate
  if(options && options.immediate) {
    job()
  } else {
    oldValue = effectFn()
  }
}